<template>
	<div class="supplier">
		<div style=" width: 100%;display: flex;justify-content: space-between;">
			<div>
				<el-button type="primary" @click="supplierDialogShow(null,0)">
					新增供应商
				</el-button>
				<el-button type="primary" @click="exportExcel" style="margin-left: 10px;">
					导出Excel
				</el-button>
			</div>
			<!-- 条件查询 -->
			<div style="display: flex;">
				<el-input v-model="suppliersName" clearable @change="getSupplierList()"
					style="width: 250px;margin-right: 10px;" placeholder="按名称,电话,地址搜索">
				</el-input>
				<!-- 地区 -->
				<el-select v-model="provinceCode" filterable placeholder="省份" :loading="regionLoading" clearable
					style="width: 120px;" @focus="getCascadeList('province')" @change="selectProvince">
					<el-option v-for="item in provinceList" :key="item.value" :label="item.province"
						:value="item.provinceCode">
					</el-option>
				</el-select>
				<el-select v-model="cityCode" filterable placeholder="市" :loading="regionLoading" clearable
					style="width: 100px;" @focus="getCascadeList('city')" @change="selectCity">
					<el-option v-for="item in cityList" :key="item.value" :label="item.city" :value="item.cityCode">
					</el-option>
				</el-select>
				<el-select v-model="areaCode" filterable placeholder="区/县" :loading="regionLoading" clearable
					style="width: 100px;" @focus="getCascadeList('area')" @change="selectArea">
					<el-option v-for="item in areaList" :key="item.value" :label="item.area" :value="item.areaCode">
					</el-option>
				</el-select>
				<el-button @click="reset()" style="margin-left: 10px;">重置</el-button>
			</div>
		</div>
		<div class="data-table">
			<el-table :data="tableData" v-loading="loading" border stripe 
				style="width: 100%" height="100%">
				<el-table-column prop="i" label="序号" width="60">
				</el-table-column>
				<el-table-column prop="suppliersName" label="供应商名称" width="200">
				</el-table-column>
				<el-table-column prop="suppliersPhone" label="联系电话" width="150">
				</el-table-column>
				<el-table-column prop="address" label="联系地址" fit>
				</el-table-column>
				<el-table-column prop="billingTotal" label="月结账单数" width="100">
				</el-table-column>
				<el-table-column prop="remark" label="备注" fit>
				</el-table-column>
				<el-table-column label="操作" width="160" fixed="right" v-if="rootShow()">
					<template slot-scope="scope">
						<el-button v-if="userInfo.roleId === '1'" size="medium" type="text"
							@click="supplierDialogShow(scope.row.id,1)">
							编辑
						</el-button>
						<el-divider v-if="userInfo.roleId === '1'" direction="vertical">
						</el-divider>
						<el-button v-if="userInfo.roleId === '1'" size="medium" type="text"
							@click="deleteSupplier(scope.row)">
							删除
						</el-button>
						<el-divider v-if="userInfo.roleId === '1'" direction="vertical">
						</el-divider>
						<el-button v-if="rootShow()" size="medium" type="text" @click="billing(scope.row)">
							账单
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="currentPage" :page-sizes="[20, 50, 100]" :page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</div>
		<!-- 新增/详情 -->
		<el-dialog :title="title" :visible.sync="dialogVisible" width="40%" @close="supplierDialogClose">
			<el-form ref="supplierForm" :model="selectSupplier" :rules="rules" label-width="100px">
				<el-form-item label="供应商名称" prop="suppliersName">
					<el-input v-model="selectSupplier.suppliersName" placeholder="请输入供应商名称">
					</el-input>
				</el-form-item>
				<el-form-item label="联系电话" prop="suppliersPhone">
					<el-input v-model="selectSupplier.suppliersPhone" placeholder="请输入联系电话">
					</el-input>
				</el-form-item>
				<el-form-item label="省市区" prop="district">
					<div id="app">
						<el-cascader v-model="selectedOptions" size="large" :options="pcaTextArr" @change="change">
						</el-cascader>
					</div>
				</el-form-item>
				<el-form-item label="详细地址" prop="suppliersAddress">
					<el-input v-model="selectSupplier.suppliersAddress" placeholder="请输入详细地址">
					</el-input>
				</el-form-item>
				<el-form-item label="备注">
					<el-input v-model="selectSupplier.remark" placeholder="请输入备注">
					</el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addSuppliers">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import warehouseApi from '../../../api/warehouse';
	import regionApi from '../../../api/region';
	import {
		pcaTextArr
	} from "element-china-area-data";
	export default {
		data() {
			return {
				userInfo: {},
				selectSupplier: {
					id: null,
					suppliersName: null,
					suppliersPhone: null,
					province: null,
					city: null,
					district: null,
					suppliersAddress: null,
					remark: null
				},
				title: "新增供应商",
				dialogVisible: false,
				suppliersName: null,
				tableData: [],
				loading: false,
				currentPage: 1,
				pageSize: 50,
				total: 0,
				regionLoading: false,
				provinceCode: null,
				cityCode: null,
				areaCode: null,
				provinceList: [],
				cityList: [],
				areaList: [],
				pcaTextArr,
				selectedOptions: null,
				rules: {
					suppliersName: [{
						required: true,
						message: '请输入供应商名称',
						trigger: 'blur'
					}],
					suppliersPhone: [{
						required: true,
						message: '请输入联系电话',
						trigger: 'blur'
					}],
					district: [{
						required: true,
						message: '请选择地区',
						trigger: 'blur'
					}],
					suppliersAddress: [{
						required: true,
						message: '请输入详细地址',
						trigger: 'blur'
					}]
				}
			}
		},
		created() {
			this.userInfo = JSON.parse(localStorage.getItem("userInfo"))
			this.getSupplierList();
		},
		methods: {
			// 获取供应商列表
			getSupplierList() {
				this.loading = true;
				let province = null;
				let city = null;
				let district = null;
				if (this.provinceCode !== null && this.provinceCode !== '') {
					const region = this.provinceList.filter(item => item.provinceCode === this.provinceCode)
					province = region[0].province
				}
				if (this.cityCode !== null && this.cityCode !== '') {
					const region = this.cityList.filter(item => item.cityCode === this.cityCode)
					city = region[0].city
				}
				if (this.areaCode !== null && this.areaCode !== '') {
					const region = this.areaList.filter(item => item.areaCode === this.areaCode)
					district = region[0].area
				}
				const data = {
					suppliersName: this.suppliersName,
					province: province,
					city: city,
					district: district,
					currentPage: this.currentPage,
					pageSize: this.pageSize,
				}
				warehouseApi.getSuppliersList(data).then(res => {
					if (res.code === 200) {
						this.total = res.data.total
						this.tableData = res.data.suppliersVoList.map((item, index) => {
							item.i = (this.currentPage - 1) * this.pageSize + index + 1;
							item.address = item.province + item.city + item.district + item
								.suppliersAddress
							return item;
						})
					}
				}).finally(() => {
					this.loading = false;
				})
			},
			// pageSize变化
			handleSizeChange(pageSize) {
				this.pageSize = pageSize
				this.getSupplierList()
			},
			// 页码变化
			handleCurrentChange(curPage) {
				this.currentPage = curPage
				this.getSupplierList()
			},
			// 重置数据
			resetData() {
				this.selectSupplier = {
					id: null,
					suppliersName: null,
					suppliersPhone: null,
					province: null,
					city: null,
					district: null,
					suppliersAddress: null,
					remark: null
				}
				this.selectedOptions = new Array();
			},
			// 重置查询条件
			reset() {
				this.currentPage = 1;
				this.pageSize = 50;
				this.suppliersName = null;
				this.provinceCode = null;
				this.cityCode = null;
				this.areaCode = null;
				this.getSupplierList();
			},
			// 获取地区
			getCascadeList(value) {
				let data = {};
				if (value === 'city') {
					this.cityList = []
					if (this.provinceCode === null || this.provinceCode === '') {
						return;
					}
					data = {
						provinceCode: this.provinceCode
					}
				} else if (value === 'area') {
					this.areaList = []
					if (this.cityCode === null || this.cityCode === '') {
						return;
					}
					data = {
						cityCode: this.cityCode
					}
				}
				this.regionLoading = true;
				regionApi.getCascadeList(data).then(res => {
					if (res.code === 200) {
						if (value === 'province') {
							this.provinceList = res.data
						} else if (value === 'city') {
							this.cityList = res.data
						} else if (value === 'area') {
							this.areaList = res.data
						}
					}
				}).finally(() => {
					this.regionLoading = false;
				})
			},
			// 选择省
			selectProvince(value) {
				// 重置市代码
				this.cityCode = null
				// 清空市列表
				this.cityList = []
				// 重置区/县代码
				this.areaCode = null
				// 清空区/县列表
				this.areaList = []
				// 查询客户列表
				this.getSupplierList();
			},
			// 选择市
			selectCity(value) {
				// 重置区/县代码
				this.areaCode = null
				// 清空区/县列表
				this.areaList = []
				// 查询客户列表
				this.getSupplierList();
			},
			// 选择区/县
			selectArea(value) {
				this.getSupplierList();
			},
			// 打开新增/编辑弹窗
			supplierDialogShow(id, index) {
				if (index === 0) {
					// 新增
					this.title = "新增供应商"
					this.dialogVisible = true;
				} else if (index === 1) {
					this.title = "编辑供应商"
					// 编辑
					const data = {
						id: id
					}
					warehouseApi.getSuppliers(data).then(res => {
						if (res.code === 200) {
							this.selectSupplier = res.data
							let province = this.selectSupplier.province;
							if (this.selectSupplier.province === "北京" ||
								this.selectSupplier.province === "天津") {
								province = this.selectSupplier.province + "市"
							}
							this.selectedOptions = [
								province,
								this.selectSupplier.city,
								this.selectSupplier.district
							]
							this.dialogVisible = true;
						}
					})
				}
			},
			// 关闭弹窗
			supplierDialogClose() {
				// 重置数据
				this.resetData();
				this.$refs.supplierForm.resetFields();
			},
			// 提交数据
			addSuppliers() {
				this.$refs.supplierForm.validate((valid) => {
					if (valid) {
						if (this.selectSupplier.id === null) {
							// 添加
							warehouseApi.addSuppliers(this.selectSupplier).then(res => {
								if (res.code === 200) {
									this.$message.success("添加成功")
									this.resetData()
									this.reset()
									this.dialogVisible = false;
								}
							})
						} else {
							// 修改
							warehouseApi.updateSuppliers(this.selectSupplier).then(res => {
								if (res.code === 200) {
									this.$message.success("添加成功")
									this.resetData()
									this.reset()
									this.dialogVisible = false;
								}
							})
						}
					} else {
						this.$message.error("请将表单填写完整！")
					}
				});
			},
			// 地区改变
			change(e) {
				this.selectSupplier.province = e[0]
				this.selectSupplier.city = e[1]
				this.selectSupplier.district = e[2]
			},
			// 删除供应商
			deleteSupplier(item) {
				this.$confirm(`确定要删除该供应商吗？[${item.suppliersName}]`, "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					const data = {
						id: item.id
					}
					warehouseApi.deleteSuppliers(data).then(res => {
						if (res.code === 200) {
							this.$message.success("删除成功");
							this.reset();
						}
					})
				})
			},
			// 账单详情
			rootShow() {
				if (this.userInfo.roleId === '1' || this.userInfo.roleId === '6') {
					return true;
				}
				return false;
			},
			// 账单
			billing(row) {
				localStorage.setItem("supplierId", row.id)
				this.$router.push({
					path: "/warehouse/supplier/SupplierBilling"
				})
			},
			//导出Excel
			exportExcel() {
				const data = this.formatData(this.tableData); // 将数据格式化为xlsx可以识别的格式
				const wb = this.$XLSX.utils.book_new();
				const ws = this.$XLSX.utils.json_to_sheet(data);
				// 设置列宽
				const columnWidths = [
					{wch: 5},
					{wch: 30}, // 供应商名称列宽度
					{wch: 15}, // 联系电话列宽度
					{wch: 50}, // 联系地址列宽度
					{wch: 25} // 备注列宽度
				];
				ws['!cols'] = columnWidths;
				this.$XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
				this.$XLSX.writeFile(wb, "供应商信息.xlsx");
			},
			formatData(data) {
				// 格式化表格数据，将对象数组转换为数组对象
				return data.map((item) => {
					const {
						i,
						suppliersName,
						suppliersPhone,
						address,
						remark
					} = item;
					return {
						序号: i,
						供应商名称: suppliersName,
						联系电话: suppliersPhone,
						联系地址: address,
						备注: remark,
					};
				});
			},
		}
	}
</script>

<style>
	.supplier {
		height: 100%;
	}

	.data-table {
		height: 94%;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: center;
		margin-top: 10px;
	}
</style>